//
//  HomeVC+Function.swift
//  WatermarkCamera
//
//  Created by 赵新 on 5/7/2024.
//

import UIKit
import AxcBedrock

// MARK: - [HomeVC.VideoRecordState]

extension HomeVC {
    /// 视频录制状态
    enum VideoRecordState {
        /// 停止
        case stop
        /// 进行中
        case being
        /// 暂停
        case pause
    }
}

extension HomeVC {
    /// 切换中部UI模式
    func switchMode(_ functionMode: HomeModeView.Mode) {
        controlView.isIgnoreWatermarkFrames = false // 增加水印透传
        controlView.dottedLayer.strokeColor = UIColor.white.cgColor
        // 旋转方向控制
        isAccelerometerFeedback = true
        vm.defaultOrientation = [
            .unknown, .portrait, .portraitUpsideDown, .landscapeLeft, .landscapeRight, .faceUp,
            .faceDown,
        ]
    }

    /// 设置初始清晰度
    func setInitialArticulation() {
        if let cacheArticulation = UserDefaults.standard.object(forKey: "Camera_VideoArticulation") as? Int,
           let articulation: VideoBuffer.Articulation = .init(rawValue: cacheArticulation) {
            menuView.articulationBtn.articulation = articulation
        } else {
            menuView.articulationBtn.articulation = ._720p
        }
        cameraView?.setWriterArticulation(menuView.articulationBtn.articulation)
    }

    /// 适配布局
    func autoFrame() {
        var cameraBounds = cameraContentView.frame
        watermarkContentView.frame = cameraBounds
        watermarkContentView.axc.set(width: ScreenWidth)
        controlView.frame = cameraBounds
        controlView.axc.set(width: ScreenWidth)
        let headerViewFrame = headerView.frame
        var height = cameraBounds.height
        if !headerView.isTransparent { // 透明
            height -= headerViewFrame.height
        }
    }

    /// 设置重力感应
    func deviceMotionGravitySensor() {
        // 进行监听
        MotionTool.shared.orientation.subscribe(onNext: { [weak self] orientation in
            guard let weakSelf = self else { return }
            // 震动反馈
            if weakSelf.isAccelerometerFeedback {
                AxcDevice.PlayShake(.light)
            }
            // 布局转向
            weakSelf.setControlOrientation(orientation)
        }).disposed(by: rx.disposeBag)
    }

    /// 根据重感设置按钮匹配方向
    func setControlOrientation(_ orientation: UIDeviceOrientation) {
        // 询问外部代理支持的方向
        var defaultOrientation: [UIDeviceOrientation] = vm.defaultOrientation
        guard defaultOrientation.contains(orientation) else { return }
        var angle = 0
        switch orientation {
        case .portrait: // 正常
            angle = 0
        case .landscapeLeft: // 左
            angle = 90
        case .landscapeRight: // 右
            angle = -90
        case .portraitUpsideDown: // 反向
            angle = 180
        default: break
        }

        let transform = CGAffineTransform(rotationAngle: CGFloat(angle).axc.angleToRadian)

        // 水印转向
        watermarkContentView.transform = transform
        // 控制器
        controlView.transform = transform

        autoFrame()
        // 转向用透明度动画
        watermarkContentView.alpha = 0
        controlView.alpha = 0
        UIView.animate(withDuration: 0.3) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.watermarkContentView.alpha = 1
            weakSelf.controlView.alpha = 1
        }
        // 水印虚线框闪烁
        AxcGCD.Delay(delay: 0.5) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.controlView.flashDottedLayer()
        }
    }

    /// 顶部菜单动画
    func headerMenuAnimation() {
        headerMenuShow(menuView.isHidden)
    }

    /// 顶部菜单展示/隐藏
    func headerMenuShow(_ isShow: Bool) {
        view.bringSubviewToFront(menuView) // 前置视图
        ViewSpringAnimation(menuView, isShow: isShow)
    }

    /// 开启相机
    func startCamera() {
        // 判断权限开启，和权限弹窗有关0x000000013a811600
        let cameraStatus = AuthorizedManager.camera()
        if cameraStatus.info.isAvailable {
            cameraView?.beginCapture()
        } else {
            print("无相机访问权限！status：\(cameraStatus)")
        }
    }

    /// 停止相机
    func stopCamera() {
        cameraView?.endCapture()
        // TODO: 橙哥发现的GPUImage需要释放相关内存
        GPUImageContext.sharedFramebufferCache()?.purgeAllUnassignedFramebuffers()
        GPUImageContext.setActiveShaderProgram(nil)
    }

    /// 添加相机
    func addCameraView() {
        cameraView = CameraView()
        guard let cameraView = cameraView else { return }
        cameraContentView.addSubview(cameraView)
        cameraView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        setInitialAspectRatio()
        controlView.setCameraView(cameraView)
    }

    /// 设置初始画幅
    func setInitialAspectRatio() {
        if let function = modeView.firstSelectFunction() {
            switch function {
            case .photo: // 设置相机画幅比为4：3默认，缓存
                if let cacheAspectRatio = UserDefaults.standard.object(forKey: "Camera_AspectRatio") as? Int,
                   let aspectRatio: Eyepiece.AspectRatio = .init(rawValue: cacheAspectRatio) {
                    menuView.aspectRatioBtn.aspectRatio = aspectRatio
                    setAspectRatio(aspectRatio, animated: false)
                    photoAspectRatio = aspectRatio
                } else {
                    setAspectRatio(animated: false)
                    photoAspectRatio = .ar_4_3
                }
            case .video: // 视频画幅比永远16:9
                setAspectRatio(.ar_16_9, animated: false)
            }
        }
    }

    /// 点击翻转
    func clickFlip() {
        AxcDevice.PlayShake(.medium)
        cameraView?.rotateCamera()
        cameraView?.setExposure(0)
        // 重置焦距倍数显示
        focusAdjustView.set(scale: 1.0, isShowScales: false)
    }

    func showWatermarkAlertView() {
        // 隐藏相机上水印
        watermarkContentView.isHidden = true
        controlView.isHidden = true
        // 加载水印
        watermarkSelectView.show(selectWatermark: watermarkContentView.watermarkModel)
    }

    /// 更新水印
    func updateWatermarkView() {
        watermarkContentView.updateWatermark()
    }

    /// 点击本地相册
    func clickLocalAlbumBtn() {
        // 权限判断
        let photoAlbumStatus = AuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable {
            DataManager.searchMediaData(page: 1, pageSize: 20) { [weak self] list in
                guard let weakSelf = self else { return }

                // 如果图片空，则返回
                guard list.count > 0 else {
//                    HudManager.toast("暂无图片")
                    return
                }
                // 需要关相机
                weakSelf.stopCamera()

                let browseVM = MediaBrowseVM()
                browseVM.albumType = .local
                browseVM.mediaList = weakSelf.vm.localMediaAlbumPhotoListRelay.value.asMediaList
                browseVM.dataSourceList = weakSelf.vm.localMediaAlbumPhotoListRelay.value
//                browseVM.currentMediaWatermarkBlock = { idx in
//                    let dbModel = weakSelf.viewModel.localMediaAlbumPhotoListRelay.value[idx]
//                    let wmJson = dbModel.mediaInfoType.watermarkJson
//                    let wmc = WatermarkDetailModel.deserialize(from: wmJson)
//                    return wmc
//                }
                // 事件回调
                browseVM.actionBlock = { [weak self] type, index, vm in
                    guard let weakSelf = self else { return }
                    let imageList = weakSelf.vm.localMediaAlbumPhotoListRelay.value
                    guard let dbImage = imageList.axc.object(at: index) else { return }
                    switch type {
                    case .delete:
                        vm.presentDeleteAlert { [weak self] in
                            DataManager.deleteMedia(id: dbImage.id) { [weak self] result in
                                guard let weakSelf = self else { return }
                                if result {
                                    weakSelf.vm.syncLocalAlbumList()
                                    vm.remove(at: index)
//                                    HudManager.toast("删除成功")
                                }
                            }
                        }
                    default: break
                    }
                }
                let vc = MediaBrowseVC(browseVM)
                weakSelf.navigationController?.pushViewController(vc, animated: true)
            }
        } else {
            AuthorizedManager.showPrivacyAlert(type: .photoAlbum)
        }
    }

    /// 左下角预览按钮的图片替换
    func setPreViewImage() {
        // 相册权限判断
        let photoAlbumStatus = AuthorizedManager.photoAlbum()
        if photoAlbumStatus.info.isAvailable, // 有权
           let previewImagePath = vm.localMediaAlbumPhotoListRelay.value.first?.previewImagePath,
           let previewImage = UIImage(contentsOfFile: previewImagePath) {
            footerView.localAlbumBtn.setImage(previewImage)
        } else {
            footerView.localAlbumBtn.setImage("xiangce".axc.uiImage)
        }
    }
    
    /// 重置相机焦距
    func resetCameraFocusScale() {
        let scale: CGFloat = 1.0
        controlView.setCameraZoomFactor(scale: scale, slient: true)
        focusAdjustView.set(scale: scale, isShowScales: false)
    }
}
